package com.fivefu.core.camera.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.camera.entity.DbMonitorCamera;
import com.fivefu.core.camera.entity.DbMonitorCameraLabel;
import com.fivefu.core.camera.entity.DbMonitorLabel;
import com.fivefu.core.camera.services.*;
import com.fivefu.core.camera.vo.request.DbMonitorCameraVo;
import com.fivefu.core.camera.vo.request.ProSourcePage;
import com.fivefu.core.camera.vo.response.ProPageList;
import com.fivefu.core.camera.vo.response.ProSourcePageList;
import com.fivefu.core.data.entity.DbFfskyeyeChannel;
import com.fivefu.core.data.entity.DbFfskyeyeDevice;
import com.fivefu.core.data.mapper.DbFfskyeyeDeviceMapper;
import com.fivefu.core.data.services.DbFfskyeyeChannelService;
import com.fivefu.core.data.services.DbFfskyeyeDeviceService;
import com.fivefu.module.dictionary.entity.DbSysDict;
import com.fivefu.module.dictionary.service.DbSysDictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MonitorCameraServiceImpl implements MonitorCameraService {

    private Logger logger = LoggerFactory.getLogger(MonitorCameraServiceImpl.class);


    @Autowired
    private DbFfskyeyeDeviceMapper dbFfskyeyeDeviceMapper;
    @Autowired
    private DbFfskyeyeChannelService dbFfskyeyeChannelService;
    @Autowired
    private DbFfskyeyeDeviceService dbFfskyeyeDeviceService;
    @Autowired
    private DbMonitorCameraService dbMonitorCameraService;

    @Autowired
    private RegionService regionService;

    @Autowired
    private DbMonitorCameraLabelService dbMonitorCameraLabelService;

    @Autowired
    private DbMonitorLabelService dbMonitorLabelService;

    @Autowired
    private DbSysDictService dbSysDictService;
    /**
     * 同步探头
     */
    @Override
    public void synCameraInfo(){
        List<DbFfskyeyeChannel> channelList = dbFfskyeyeChannelService.queryChannelList(0, null);
        List<DbFfskyeyeDevice> deviceList = dbFfskyeyeDeviceService.queryDevicelList(0, null);
        Map<Long, DbFfskyeyeDevice> deviceMap = deviceList.stream().collect(Collectors.toMap(k -> k.getId(), v -> v));

        List<DbMonitorCamera> cameraList = dbMonitorCameraService.queryMonitorCameraList();
        Map<String, DbMonitorCamera> cameraMap = cameraList.stream().collect(Collectors.toMap(k -> k.getCameraCode(), v -> v));


        for (DbFfskyeyeChannel channel : channelList){
            String code = channel.getChannelCode();
            Long deviceID = channel.getDeviceId();

            if (cameraMap.containsKey(code)){
                DbMonitorCamera camera = cameraMap.get(code);
                if (camera != null){
                    camera.setOnlineStatus(channel.getOnline() + "");
                    if (channel.getIsDelete().equals(1)){
                        camera.setCameraStatus("1");
                    }else{
                        camera.setCameraStatus("0");
                    }
                    dbMonitorCameraService.editMonitorCamera(camera,null);
                }
            }else if (deviceMap.containsKey(deviceID)){
                DbFfskyeyeDevice device = deviceMap.get(deviceID);
                DbMonitorCamera camera = new DbMonitorCamera();
                camera.setCameraLongitude(channel.getLongitude());//经度
                camera.setCameraLatitude(channel.getLatitude());//纬度
                camera.setCameraName(channel.getChannelName());//名称
                camera.setCameraCode(channel.getChannelCode());//编号
                camera.setOnlineStatus(channel.getOnline() + "");//在线状态
                camera.setCameraManufacturer(device.getDeviceManufacturer());//厂商
                camera.setCameraType(channel.getCameraType());//类型
                //探头状态
                if (channel.getIsDelete().equals(1)){
                    camera.setCameraStatus("1");
                }else{
                    camera.setCameraStatus("0");
                }
                dbMonitorCameraService.editMonitorCamera(camera,null);
            }
        }
    }

    /**
     * 同步探头在线状态
     */
    @Override
    public void synCameraOnlineStatus(){
        List<DbFfskyeyeChannel> channelList = dbFfskyeyeChannelService.queryChannelList(0, null);

        List<DbMonitorCamera> cameraList = dbMonitorCameraService.queryMonitorCameraList();
        Map<String, DbMonitorCamera> cameraMap = cameraList.stream().collect(Collectors.toMap(k -> k.getCameraCode(), v -> v));

        for (DbFfskyeyeChannel channel : channelList){
            String code = channel.getChannelCode();
            if (cameraMap.containsKey(code)){
                DbMonitorCamera camera = cameraMap.get(code);
                if (camera != null){
                    dbMonitorCameraService.changeCameraOnlineStatus(camera.getId(), channel.getOnline() + "");
                }
            }
        }
    }

    /**
     *
     * 将 DbMonitorCamera数据集合转化为 ProPageList集合
     * @param list 探头集合
     */
    @Override
    public List<ProPageList> cameraListToPageList(List<DbMonitorCamera> list) {
        List<ProPageList> pageLists = new ArrayList<>();
        if (list != null && list.size() > 0){
            list.stream().forEach(camera->{
                ProPageList proPageList = new ProPageList();
                BeanUtils.copyProperties(camera,proPageList);
                if (StrUtils.isNotNull(camera.getCameraAreaid())) {
                    proPageList.setCameraAreaName(regionService.queryAreaNameByCode(camera.getCameraAreaid()));
                }
                //将厂商用数字字典转换
                if (StrUtils.isNotNull(proPageList.getCameraManufacturer())) {
                    DbSysDict dict = dbSysDictService.queryDictDetail(null, proPageList.getCameraManufacturer());
                    if (null != dict ) {
                        proPageList.setCameraManufacturer(dict.getDictName());
                    }
                }
                //转换探头的状态
                if (StrUtils.isNotNull(proPageList.getCameraStatus())) {
                    if ("0".equals(proPageList.getCameraStatus())) {//离线
                        proPageList.setCameraStatus("离线");
                    } else if ("1".equals(proPageList.getCameraStatus())) {//在线
                        proPageList.setCameraStatus("在线");
                    }
                }
                //探头类型返回格式转换
                if (StrUtils.isNotNull(proPageList.getCameraType())) {
                    DbSysDict dict = dbSysDictService.queryDictDetail(null, proPageList.getCameraType());
                    if (null != dict) {
                        proPageList.setCameraType(dict.getDictName());
                    }
                }

                pageLists.add(proPageList);
            });
        }
        return pageLists;
    }

    /**
     *
     * 通过探头id查询该探头的标签
     * @param id 探头id
     * @return List<Map<String,String>>  key:labelName value:cameraCode
     */
    @Override
    public List<Map<String, String>> queryCameraLabelById(Long id) {
        List<Map<String, String>> maps = new ArrayList<>();
        DbMonitorCamera dbMonitorCamera = dbMonitorCameraService.getById(id);
        if (dbMonitorCamera != null){
            String cameraCode = dbMonitorCamera.getCameraCode();
            QueryWrapper<DbMonitorCameraLabel> wrapper = new QueryWrapper<>();
            wrapper.eq("is_delete",0).eq("camera_code",cameraCode);
            List<DbMonitorCameraLabel> list = dbMonitorCameraLabelService.list(wrapper);
            if (list != null && list.size() > 0){
                for (DbMonitorCameraLabel dbMonitorCameraLabel : list) {
                    DbMonitorLabel byId = dbMonitorLabelService.getById(dbMonitorCameraLabel.getLabelId());
                    if (byId != null){
                        Map<String, String> map = new HashMap<>();
                        map.put(byId.getLabelName(),cameraCode);
                        maps.add(map);
                    }
                }
            }
        }
        return maps;
    }

    /**
     *
     * 分页查询探头源数据列表
     * @param proPage  数据源分页查询参数
     */
    @Override
    public Page<ProSourcePageList> getProbeSourcePageList(ProSourcePage proPage) {
        IPage iPage = new Page<DbFfskyeyeDevice>(proPage.getPage(),proPage.getLimit());
        Page<ProSourcePageList> page = dbFfskyeyeDeviceMapper.queryDeviceList(iPage, proPage.getDeviceModel(), proPage.getDeviceName(), proPage.getChannelType(), proPage.getDeviceManufacturer(), proPage.getDeviceSerialNum(), proPage.getOnlineStatus());
        return page;
    }

    /**
     *
     * 分页查询探头列表
     *
     * @param page  探头id集合 为标签管理部分服务
     * @param limit
     * @param cameraCode
     * @param cameraName
     * @param cameraType
     * @param cameraManufacturer
     * @param cameraAreaid
     * @param cameraStreetid
     * @param cameraStatus
     */
    @Override
    public Page<ProPageList> getProbePageList(Integer page,Integer limit,String cameraCode,String cameraName,String cameraType,String cameraManufacturer,String cameraAreaid,String cameraStreetid,String cameraStatus,String onlineStatus) {
        Page<ProPageList> returnPage = new Page<>();
        Page<DbMonitorCamera> dbMonitorCameraPage = dbMonitorCameraService.queryCameraList(cameraName, cameraCode, cameraType, cameraAreaid,cameraStreetid, cameraStatus, onlineStatus, cameraManufacturer, null, null, page, limit);
        List<DbMonitorCamera> cameraList = dbMonitorCameraPage.getRecords();
        returnPage.setTotal(dbMonitorCameraPage.getTotal());

        //响应类赋值
        List<ProPageList> proPageLists = cameraListToPageList(cameraList);
        returnPage.setRecords(proPageLists);
        return returnPage;
    }

    /**
     *
     * 编辑探头信息
     * @param cameraVo 探头参数
     * @param userid 操作用户编号
     */
    @Override
    public boolean editMonitorCamera(DbMonitorCameraVo cameraVo, String userid) {
        DbMonitorCamera dbMonitorCamera = new DbMonitorCamera();
        BeanUtils.copyProperties(cameraVo,dbMonitorCamera);
        //处理探头
        dbMonitorCameraService.editMonitorCamera(dbMonitorCamera,userid);
        //处理探头标签
        List<Long> labelIds = cameraVo.getLabelIds();
        if (labelIds != null && labelIds.size() > 0){
            dbMonitorCameraLabelService.editMonitorCameraLabel(cameraVo.getCameraCode(),labelIds,userid);
        }
        return true;
    }
}
